<?php
namespace Manage\Controller;

use Think\Controller;
use Think\Model;

class PurchaseController extends BaseController
{

    public function index()
    {
        $page = max(I('get.p'), 1);
        $num = max(I('get.num'), 20);
        $search_field = I('get.search_field');
        $search = I('get.search');

        $order_field = I('get.order_field', 'last_modify');
        $order = I('param.order', 'desc');

        $sunxu = $order == 'asc' ? 'desc' : 'asc';
        $this->assign('order', $sunxu);
        $this->assign('p', $page);

        if ($order_field && $order) {
            $order = "{$order_field} {$order}";
            $this->assign('order_field', $order_field);
        } else {
            $order = " last_modify desc";
        }

        $status = I('get.view', '0');
        if ($status) {
            $view = $status;
        } else {
            $view = '0';
        }
        $this->assign('view', $view);
        $where[] = ' 1=1 ';
        if ($status !== '' && $status != 4) {
            $where[] = array('status'=>$status);
        }
        if ($search && $search_field) {
            $where[] = $search_field." like '%".$search."%'";
            $this->assign('search', $search);
            $this->assign('search_field', $search_field);
        }
        $count = M('b2c_purchase a')
            ->join(C('DB_PREFIX').'webpos_local_store b on a.local_id=b.local_id')
            ->where($where)
            ->count();

        $Page = new \Think\Page($count, $num);
        $show = $Page->show();
        $fields = array(
            'a.*',
            'b.local_name',
            'b.principal',
            'b.tel',
            'b.mobile',
            'b.local_type',
            'b.local_number',
        );
        $list = M('b2c_purchase a')
            ->join(C('DB_PREFIX').'webpos_local_store b on a.local_id=b.local_id')
            ->where($where)
            ->field($fields)
            ->order($order)
            ->page($page, $num)
            ->select();
        $this->assign('list', $list);
        $this->assign('page', $show);
        $this->display();
    }

    /**
     *
     * select  a.*,c.name,d.* from sdb_b2c_purchase_product a
    INNER JOIN sdb_b2c_product_relation b ON a.product_id=b.product_id
    LEFT JOIN sdb_b2c_products c on a.product_id = c.product_id
    LEFT JOIN (

    select x.product_id xid,x.vendor_price,x.vendor_sum,y.vendor_name from sdb_b2c_vendor_product x
    INNER JOIN sdb_b2c_vendors y on x.vendor_id=y.vendor_id

    ) d on a.product_id = d.xid
     *
     *
     */
    public function products() {
        $purc_id = I('get.purc_id');
        if (!$purc_id) {
            $this->error('错误,缺少参数');
        }
        $this->assign('purc_id', $purc_id);
        //分页
        $p = max(I('param.p'), 1);
        $num = max(I('param.num'), 20);
        $this->assign('p', $p);
        $this->assign('num', $num);

        //排序
        $order_field = I('param.order_field', 'product_id');
        $order = I('param.order', 'desc');
        $this->assign('order_field', $order_field);
        $sunxu = $order == 'asc' ? 'desc' : 'asc';
        $this->assign('order', $sunxu);

        $order = array($order_field => $order);

        //搜索
        $search_field = I('param.search_field');
        $search = trim(I('param.search'));
        $where[0] = ' 1=1 ';
        if ($search && $search_field) {
            $where[] = $search_field." like '%".$search."%'";
            $this->assign('search',$search);
            $this->assign('search_field',$search_field);
        }
        $where[] = array(
            'purc_id'=>$purc_id,
        );
        //求和
        $count = M('b2c_purchase_product a')
            ->join(C('DB_PREFIX').'b2c_products c on a.product_id = c.product_id and c.disabled="false"')
            ->where($where)
            ->count();

        //分页输出
        $Page = new \Think\Page($count, $num);
        $show = $Page->show();

        $fields = array(
            'purc_price',
            'purc_sum',
            'name',
            'c.spec_info',
            'c.barcode',
            'c.bn',
            'a.product_id',
            'a.goods_id',
        );
        //列表
        $data = M('b2c_purchase_product a')
            ->join(C('DB_PREFIX').'b2c_products c on a.product_id = c.product_id and c.disabled="false"')
            ->where($where)
            ->field($fields)
            ->page($p, $num)
            ->order($order)
            ->select();

        $this->assign('list',$data);
        $this->assign('page',$show);
        $this->display();
    }

    public function getVendors() {
        $product_id = I('param.product_id');
        if (!$product_id) {
            $return = array(
                'status' => false,
                'message' => '失败',
            );
            $this->ajaxReturn($return);
        }
        $order = 'vendor_price asc, vendor_sum desc';
        $where = array(
            'a.product_id' => $product_id,
            'product_type_id' => '2',
        );
        $fields = array(
            'a.vendor_id',
            'vendor_price',
            'vendor_sum',
            'vendor_name'
        );
        $list = M('b2c_vendor_product a')
            ->join(C('DB_PREFIX').'b2c_vendors b on a.vendor_id=b.vendor_id')
            ->join(C('DB_PREFIX').'b2c_product_relation c on a.product_id=c.product_id')
            ->field($fields)
            ->where($where)
            ->order($order)
            ->select();

        $this->assign('list',$list);
        $content = $this->fetch('Purchase:getVendors');
        $this->show($content);
    }

    public function change_status() {
        if (!IS_AJAX) {
            $return = array(
                'status' => false,
                'message' => '错误的请求方式',
            );
        }
        $purc_id = I('post.purc_id');
        $before = I('post.before' ,'0');
        $status = I('post.status', false);
        $desc = I('post.desc');
        if (!$purc_id || $status === false) {
            $return = array(
                'status' => false,
                'message' => '参数缺失',
            );
        }

        if($return) {
            $this->ajaxReturn($return);
        }
        //todo 加入管理员信息 id和name
        //写入日志表
        $log = array(
            'purc_id' => $purc_id,
            'manage_id' => 1, //默认给个1 以后在修改
            'manage_name' => 'admin', //以后修改
            'role' => '0', //0-平台 1-门店
            'before' => $before,
            'later' => $status,
            'desc' => $desc,
            'create_time' => time(),
        );
        $db = new Model();
        $db->startTrans();
        $logs = M('b2c_purchase_logs')->add($log);
        $save = array(
            'status' => (string) $status,
            'last_modify'=>time(),
        );
        $res = M('b2c_purchase')->where(array('purc_id'=>$purc_id))->save($save);
        if ($logs !== false && $res !== false) {
            $db->commit();
        } else {
            $db->rollback();
        }
        if ($res) {
            $return = array(
                'status' => true,
                'message' => '成功',
            );
        } else {
            $return = array(
                'status' => true,
                'message' => '失败',
            );
        }
        $this->ajaxReturn($return);
    }

    public function get_purchase_logs() {
        $purc_id = I('get.purc_id');
        if (!$purc_id) {
            $return = array(
                'status' => true,
                'message' => '参数缺失',
            );
            $this->ajaxReturn($return);
        }
        $logs = M('b2c_purchase_logs')
            ->where(array('purc_id'=>$purc_id))
            ->select();
        $statuss = array('已提交', '处理中', '已完成', '已取消');
        if ($logs) {
            foreach ($logs as &$item) {
                $item['before_status'] = $statuss[$item['before']];
                $item['later_status'] = $statuss[$item['later']];
                $item['create_time'] = date('Y-m-d H:i:s', $item['create_time']);
            }
        }
        $this->ajaxReturn($logs);
    }

    private function _sql($fields, $where = '', $order = '', $limit = '')
    {
        /**
         * select a.product_id,a.name,a.barcode,a.bn,a.cost,a.price,c.* from sdb_b2c_products a
         * left join
         * (select DISTINCT * from sdb_b2c_product_relation b where b.product_type_id=2) c
         * on a.product_id=c.product_id ORDER BY c.p_relation_id desc,a.product_id desc
         */
        if (is_array($fields)) {
            $fields = join(',', $fields);
        }
        return $sql = "select {$fields} from " . C('DB_PREFIX') . "b2c_products a 
        left join (select DISTINCT p_relation_id,guidance_price,product_id from " . C('DB_PREFIX') . "b2c_product_relation b where b.product_type_id=2 ) c 
        on a.product_id = c.product_id {$where} {$order} {$limit}";
    }

    /**
     * 可采购商品的配置
     */
    public function setup()
    {
        $page = max(I('param.p'), 1);
        $num = max(I('param.num'), 20);
        $search_field = I('param.search_field');
        $search = I('param.search');
        $order_field = I('param.order_field');
        $order = I('param.order', 'asc');
        $sunxu = $order == 'asc' ? 'desc' : 'asc';
        $this->assign('order', $sunxu);
        $this->assign('p', $page);
        if ($order_field && $order) {
            $order = "order by c.p_relation_id {$order}" . " ,a.{$order_field} {$order} ";
            $this->assign('order_field', $order_field);
        } else {
            $order = " order by c.p_relation_id desc,a.product_id desc ";
        }

        $where = " where a.disabled='false' ";
        if ($search && $search_field) {
            $where .= " and a.{$search_field} like '%{$search}%' ";
            $this->assign('search', $search);
            $this->assign('search_field', $search_field);
        }

        $db = new Model();
        $count = $db->query($this->_sql('count(*)', $where));
        $Page = new \Think\Page($count[0]['count(*)'], $num);
        $show = $Page->show();
        $fields = array(
            'a.product_id pid',
            'a.goods_id gid',
            'a.barcode',
            'a.bn',
            'a.name',
            'a.price',
            'a.cost',
            'a.store',
            'a.spec_info',
            'c.p_relation_id',
            'c.guidance_price',
        );
        $skip = ($page - 1) * $num;
        $limit = " limit {$skip},{$num} ";
        $list = $db->query($this->_sql($fields, $where, $order, $limit));
        $this->assign('list', $list);
        $this->assign('page', $show);
        $this->display();
    }


    public function save_edit()
    {
        $data = I('post.data');
        $type = I('get.type');
        if (isset($type) && $type == '1') {
            $type = '1';
        } else {
            $type = '2';
        }
        $db = new Model();
        $db->startTrans();
        foreach ($data as $item) {
            $res = $this->save_product($item, $type);//2->可采购商品
            if ($res === false) {
                break;
            }
        }

        if ($res !== false) {
            $db->commit();
            $return = array(
                'status' => true,
                'message' => '成功',
            );
        } else {
            $db->rollback();
            $return = array(
                'status' => false,
                'message' => '失败',
            );
        }
        $this->ajaxReturn($return);
    }

    /**保存供应商的货品编辑 如果存在执行更新 反之执行插入
     * @param $data
     * @param $vendor_id
     * @return bool
     */
    private function save_product($data, $type = 2)
    {
        if (!$type) return false;
        $where = array(
            'product_id' => $data['product_id'],
            'product_type_id' => $type,
        );
        $count = M('b2c_product_relation')->where($where)->count();

        if ($data['is_show'] == 'true' && empty($count)) {
            $arr = array(
                'goods_id' => $data['goods_id'],
                'product_id' => $data['product_id'],
                'guidance_price' => $data['guidance_price'],
                'product_type_id' => $type,
                'uptime' => time(),
                'last_modify' => time(),
            );
            $res = M('b2c_product_relation')->add($arr);
        }elseif ($data['is_show'] == 'true' && $count){
            $save =array('guidance_price' => $data['guidance_price']);
            $res = M('b2c_product_relation')->where($where)->save($save);
        }elseif ($data['is_show'] == 'false' && $count) {
            // 删除货品判断改货品是否有店铺在使用中，如果在就不能删除
            if ($type == 1) {

                $store_product = M('b2c_store_product')->field('local_id')->where(['store_status' => 'true', 'product_id' => $data['product_id']])->select();
                if (empty($store_product)) {
                    $res = M('b2c_product_relation')->where($where)->delete();
                } else {
                    //该商品已经上架 不能取消关联
                    $return = array(
                        'status' => false,
                        'message' => '该商品已经上架,不能取消关联',
                    );
                    $this->ajaxReturn($return);
                }
            }
        }
        return $res !== false ? true : false;
    }


    public function stores() {
        //分页
        $p = max(I('param.p'), 1);
        $num = max(I('param.num'), 20);
        $this->assign('p', $p);
        $this->assign('num', $num);

        //排序
        $order_field = I('param.order_field', 'local_id');
        $order = I('param.order', 'desc');
        $this->assign('order_field', $order_field);
        $sunxu = $order == 'asc' ? 'desc' : 'asc';
        $this->assign('order', $sunxu);

        $order = array($order_field => $order);

        //搜索
        $search_field = I('param.search_field');
        $search = trim(I('param.search'));
        $where[0] = ' 1=1 ';
        if ($search && $search_field) {
            $where[] = $search_field." like '%".$search."%'";
            $this->assign('search',$search);
            $this->assign('search_field',$search_field);
        }
        //求和
        $count = M('webpos_local_store')
            ->where($where)
            ->count();

        //分页输出
        $Page = new \Think\Page($count, $num);
        $show = $Page->show();

        $fields = array(
            'local_id',
            'local_name',
            'local_number',
            'local_type',
            'local_status',
            'principal',
            'tel',
            'mobile',
        );
        //列表
        $data = M('webpos_local_store')
            ->where($where)
            ->field($fields)
            ->page($p, $num)
            ->order($order)
            ->select();
        if($data) {
            foreach ($data as &$item) {
                $item['local_status_desc'] = $item['local_status'] ? '正常营业': '停业';
                if (!$item['local_type']) {
                    $item['local_type_desc'] = '自营店';
                } elseif($item['local_type'] == '1') {
                    $item['local_type_desc'] = '加盟店';
                } elseif($item['local_type'] == '2') {
                    $item['local_type_desc'] = '租赁店';
                }
            }
        }
        $this->assign('list',$data);
        $this->assign('page',$show);
        $this->display();
    }

    public function store_setup() {
        $local_id = I('param.local_id');
        if (!$local_id) $this->error('缺少参数', U('purchase/stores'));

        $p = max(I('param.p'), 1);
        $num = max(I('param.num'), 20);
        $this->assign('local_id', $local_id);
        $this->assign('p', $p);
        $this->assign('num', $num);

        //店铺信息
        $info = M('webpos_local_store')->field('local_id,local_name')->where(array('local_id'=>$local_id))->find();
        $this->assign('local_name', $info['local_name']);
        //排序
        $order_field = I('param.order_field', 'product_id');
        $order = I('param.order', 'desc');
        $this->assign('order_field', $order_field);
        $sunxu = $order == 'asc' ? 'desc' : 'asc';
        $this->assign('order', $sunxu);

        $o = array();
        $o[] = array($order_field => $order);
        //搜索
        $search_field = I('param.search_field');
        $search = trim(I('param.search'));
        $where[] = ' 1=1 ';
        if ($search && $search_field) {
            $where[] = $search_field." like '%".$search."%'";
            $this->assign('search',$search);
            $this->assign('search_field',$search_field);
        }
        $where[] = ' product_type_id=2 ';
        //求和
        $db = new Model();
        $count = $db->query($this->_store_sql('count(*)', $local_id, $where));
        //分页输出
        $Page = new \Think\Page($count[0]['count(*)'], $num);
        $show = $Page->show();

        $fields = array(
            'c.product_id',
            'c.goods_id',
            'c.name',
            'c.barcode',
            'c.bn',
            'a.guidance_price',
            'b.store',
            'b.price',
        );
        //列表
        $skip = ($p - 1) * $num;
        $limit = " limit {$skip},{$num} ";
        $sql = $this->_store_sql($fields, $local_id, $where, $o, $limit);
        $list = $db->query($sql);
        $this->assign('list',$list);
        $this->assign('page',$show);
        $this->display();
    }

    private function _store_sql($fields, $local_id, $where = '', $order = '', $limit = '')
    {
        if (is_array($fields)) {
            $fields = join(',', $fields);
        }
        if (is_array($where)) {
            $where = ' where '.join(' and ', $where);
        }
        $o = '';
        if (is_array($order) && !empty($order)) {
            if ($order[0]) {
                foreach ($order as $item) {
                    $k = end(array_keys($item));
                    $v = $item[$k];
                    $o .= " {$k} {$v},";
                }
                $o = rtrim($o, ',');
            } else {
                $k = end(array_keys($order));
                $v = $order[$k];
                $o = " {$k} {$v} ";
            }
            $o = ' order by '.$o;
        }
        $sql = "select {$fields} from " . C('DB_PREFIX') . "b2c_product_relation a 
        inner join " . C('DB_PREFIX') . "b2c_products c on a.product_id=c.product_id  and c.disabled=\"false\"
        left join (select DISTINCT price,store,product_id as pid from " . C('DB_PREFIX') . "b2c_store_p_goods where local_id={$local_id} ) b 
        on a.product_id = b.pid {$where} {$o} {$limit}";
        return $sql;
    }

    public function save_store_setup() {
        if (!IS_AJAX) {
            $return = array(
                'status' => false,
                'message' => '非法请求',
            );
            $this->ajaxReturn($return);
        }
        $local_id = I('get.local_id');
        if (!$local_id) {
            $return = array(
                'status' => false,
                'message' => '缺少参数',
            );
            $this->ajaxReturn($return);
        }
        $data = I('post.data');
        $db = new Model();
        $db->startTrans();
        foreach ($data as $item) {
            $res = $this->save_store_product($item, $local_id);
            if ($res === false) {
                break;
            }
        }

        if ($res !== false) {
            $db->commit();
            $return = array(
                'status' => true,
                'message' => '成功',
            );
        } else {
            $db->rollback();
            $return = array(
                'status' => false,
                'message' => '失败',
            );
        }
        $this->ajaxReturn($return);
    }

    private function save_store_product($data, $local_id) {
        $where = array(
            'local_id' => $local_id,
            'product_id' => $data['product_id'],
        );
        $count = M('b2c_store_p_goods')->where($where)->count();
        if ($data['is_show'] == 'true' && empty($count)) {

            $arr = array(
                'local_id' => $local_id,
                'goods_id' => $data['goods_id'],
                'product_id' => $data['product_id'],
                'price' => $data['price'],
                'store' => $data['store'],
                'uptime' => time(),
                'last_modify' => time(),
            );
            $res = M('b2c_store_p_goods')->add($arr);
        } elseif ($data['is_show'] == 'true' && $count) {
            $save = array(
                'price' => $data['price'],
                'store' => $data['store'],
                'last_modify' => time(),
            );
            $res = M('b2c_store_p_goods')->where($where)->save($save);
        } elseif ($data['is_show'] == 'false' && $count) {
            $res = M('b2c_store_p_goods')->where($where)->delete();
        }
        return $res !== false ? true : false;
    }

}